import numpy as np
import matplotlib.pyplot as plot
import pandas as pd


def min_gred(x_start, rate, num, f, g, near_zero=0.0001):
    x=x_start
    min_x=10000
    min_y=10000
    x_list=[]
    y_list=[]
    for n in range(num):
        gx=g(x)
        y=f(x)
        x_list.append(x)
        y_list.append(y)
        if min_y>y:
            min_y=y
            min_x=x
        x=x-rate*gx
        print("idx:{idx}, x:{x:.5f}, y:{y:.5f}, gx:{gx:.5f}".format(idx=n, x=x,y=y,gx=gx))
        if abs(gx)<near_zero:
            break
    print(f"min_x:{min_x:.5f}, min_y:{min_y:.5f}".format(min_x=min_x,min_y=min_y))
    x_array=np.array(x_list)
    y_array=np.array(y_list)
    plot.plot(x_array,y_array)
    plot.scatter(min_x,min_y,c='r')
    plot.show()
    return (min_x,min_y)

f=lambda x:x**2
g=lambda x:2*x
min_gred(2.0,0.1,100,f,g)
#min_gred(2.0,0.3,100,f,g)
#min_gred(2.0,1.1,100,f,g)